﻿using System;
using System.Runtime.CompilerServices;
using System.Windows.Navigation;
using System.Workflow.Activities;
using System.Workflow.Runtime;
using Bookvar.ApplicationModel;
using Bookvar.ServiceModel;
using Bookvar.UpdateProcessWorkflow;
using BookvarWpf;

namespace Bookvar
{
	internal static class Application
	{
		private static App bookvarApp;
		private static WorkflowInstance workflowInstance;
		private static WorkflowRuntime workflowRuntime;
		private static bool workflowLoaded;

		[STAThreadAttribute]
		private static void Main( string[] args )
		{
			try
			{
				StartApplication();
			}
			catch (Exception ex)
			{
				
			}
		}

		[MethodImpl( MethodImplOptions.NoInlining )]
		private static void StartApplication()
		{
			bookvarApp = new App();
			bookvarApp.InitializeComponent();
			bookvarApp.LoadCompleted += app_LoadCompleted;
			bookvarApp.Run();
			if ( workflowRuntime != null )
			{
				workflowRuntime.StopRuntime();
			}
		}

		private static void MainWindow_Closed( object sender, EventArgs e )
		{
			bookvarApp.Shutdown( 0 );
		}

		private static void app_LoadCompleted( object sender, NavigationEventArgs e )
		{
			if ( !workflowLoaded )
			{
				bookvarApp.MainWindow.Closed += MainWindow_Closed;
				StartUpdateCheckingWorkflow();
				BookvarApplication.Current.ServiceLayer.AddService<IUpdateService>( new BookvarUpdateService( workflowRuntime ) );
			}
		}

	

		private static void StartUpdateCheckingWorkflow()
		{
			if ( workflowRuntime == null )
			{
				workflowLoaded = true;
				workflowRuntime = new WorkflowRuntime();
				ExternalDataExchangeService dataService = new ExternalDataExchangeService();
				workflowRuntime.AddService( dataService );
				UpdateProcessCommunicationService service = new UpdateProcessCommunicationService();
				dataService.AddService( service );

				workflowInstance = workflowRuntime.CreateWorkflow( typeof ( UpdateProcess ) );
				workflowInstance.Start();
				service.InstanceId = workflowInstance.InstanceId;
				service.Instance = workflowInstance;
			}
		}
	}
}